/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.jit.core.load;

import java.text.MessageFormat;
import java.util.Map;

/**
 * 加载StringJavaFileObject
 */
public class JitClassLoader extends ClassLoader {

    private final Map<String, byte[]> classBytesMap;

    //class字节码初始化JitClassLoader，入参不允许为null或空集合
    public JitClassLoader(Map<String, byte[]> classBytes) {
        super(ClassLoadManager.class.getClassLoader());
        if (classBytes == null || classBytes.isEmpty()) {
            throw new IllegalArgumentException("构造JitClassLoader的字节码集合不允许为空");
        }
        this.classBytesMap = classBytes;
    }

    @Override
    protected Class<?> findClass(String className) throws ClassNotFoundException {
        if (!classBytesMap.containsKey(className)) {
            throw new ClassNotFoundException(
                    MessageFormat.format("the class to load:{0},current classes:{1}", className, getClassNames())
            );
        }
        byte[] classBytes = this.classBytesMap.get(className);
        return defineClass(className, classBytes, 0, classBytes.length);
    }

    private String getClassNames() {
        String[] names = classBytesMap.keySet().toArray(new String[0]);
        StringBuilder builder = new StringBuilder();
        for (String name : names) {
            builder.append(name).append(", ");
        }
        builder.delete(builder.length() - 2, builder.length());
        return builder.toString();
    }
}
